<template>
  <div class="d_mainFlex">
    <div class="d_treeBox">
      <div class="title">
        <h3>角色</h3>
        <i class="iconfont xinjian mr5 f16 pointer" style="color: #83a0ff" @click="addRole" />
      </div>
      <div class="d_nrBox">
        <!-- 基础数据所有分组       -->
        <div class="treeList">
          <ul>
              <li
               v-for="(item, index) in allMaterielClass"
                :key="item.dictionaryID"
                class="flex flex_between"
                :class="classIndex === index ? 'on' : ''"
                @click="changeMaterClass(item, index)"
              >
                <i
                  class="iconfont personnelIco mr5 f16s"
                  style="color: #83a0ff"
                />
                <p>{{ item.roleName }}</p>
                <div class="kuOP">
                  <el-popover
                    :ref="`popover-${index}`"
                    placement="bottom"
                    popper-class="areasPopover"
                    trigger="click"
                  >
                    <div class="areasOp">
                      <ul>
                        <li @click="updateMaClass(item)">编辑</li>
                        <li @click="deleteMaterielClass(item)">删除</li>
                      </ul>
                    </div>
                    <span slot="reference" class="el-icon-more c_3F61F1" />
                  </el-popover>
                </div>
              </li>
          </ul>
        </div>
        <div v-if="allMaterielClass.length == 0" class="p16">
          <el-skeleton :rows="10" animated />
        </div>
      </div>
    </div>
    <div class="d_main p16">
      <div class="title">
        <div class="d_navtab">
          <span
            class="pointer"
            :class="active === 0 ? 'active' : ''"
            @click="changeTab(0)"
          >权限配置</span>
          <span
            class="pointer"
            :class="active === 2 ? 'active' : ''"
            @click="changeTab(2)"
          >特殊权限</span>
          <span
            class="pointer"
            :class="active === 1 ? 'active' : ''"
            @click="changeTab(1)"
          >权限用户</span>

        </div>
      </div>
      <!-- 权限配置 S-->
      <div v-show="active === 0" class="d_nrBox flexY">
        <!-- 操作区 S-->
        <div class="d_operationBox not">
          <div class="d_btn">
            <el-button type="primary" size="small" @click="addSelect">保存配置</el-button>
          </div>
        </div>
        <!-- 操作区 E-->
        <!-- 内容 S-->
        <div class="permissionBox flexY">
          <div class="wapper">
            <div class="permission">菜单</div>
            <div class="menus">权限</div>
            <div class="other">其他</div>
          </div>
          <div class="permissionList">
              <div class="items" v-for="(treeData,idx) in selectArr" :key="idx">
                <div class="item">
                  <div class="tit">
                    <el-checkbox v-model="treeData.isHavePermission" @change="handleCheckAllChange({val: treeData, checked: $event })">
                    {{ treeData.menuName }}
                    </el-checkbox>
                  </div>
                  <checkboxTreeRender :tree-data="treeData" @handle-check-all-change="handleCheckAllChange" :num='1'/>
                </div>
                <div class="list" v-if="treeData.buttons">
                  <el-checkbox v-for="(api,index) in treeData.buttons" :key="index" v-model="api.isHavePermission" :label="api.menuCode" @change="handleCheckAllChange({val: api, checked: $event })">{{ api.buttonName }}</el-checkbox>
                </div>
              </div>
          </div>
        </div>
        <!-- 内容 E-->
      </div>
      <!-- 权限配置 E-->
      <!-- 权限用户 S-->
      <div v-show="active === 1" class="d_nrBox flexY">
        <!-- 操作区 S-->
        <div class="d_operationBox not">
          <div class="d_btn">
            <el-button type="primary" size="small" icon="el-icon-plus" @click="isperShow=true">添加成员</el-button>
          </div>
        </div>
        <!-- 操作区 E-->
        <!-- 内容 S-->
        <div class="tableCon">
          <el-table
            :data="userlList"
            border
            height="100%"
          >
            <el-table-column prop="loginAccount" label="工号" />
            <el-table-column prop="employeeName" label="姓名" />
            <el-table-column prop="employeeSexName" label="性别" />
            <el-table-column prop="mobile" label="手机号" />
            <el-table-column prop="departmentName" label="部门" />
            <el-table-column prop="roleName" label="角色" />
          </el-table>
        </div>
        <!-- 内容 E-->
      </div>
      <div v-show="active === 2"  class="d_nrBox flexY">
        <div class="tableCon">
          <el-table
            :data="permissionList"
            border
            height="100%"
          >
          <el-table-column prop="specificPermissionEnName" label="权限名称" />
          <el-table-column prop="specificPermissionDesc" label="权限描述" />
          <el-table-column prop="specificPermissionState" label="权限开关" width="100" align="center">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.isHavePower"
                @change="savePermission"
                >
              </el-switch>
            </template>
          </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
    <perCheckDialog :per-visible.sync="isperShow" @getEmployee="getEmployee" />
    <!-- <per-redio-dialog :per-visible.sync="isperShow" @getEmployee="getEmployee" /> -->
    <el-dialog
      :title="subTitle"
      :visible.sync="isAddMaterriel"
      :close-on-click-modal="false"
      custom-class="comDialog "
      width="30%"
      @close="closeDialog"
    >
      <div class="dialogDody">
        <div class="addWuliaoBox">
          <el-form
            ref="materForm"
            :model="materForm"
            :rules="materFormRules"
            label-width="auto"
            class="dialogForm dialogInlineForm"
          >
            <el-row>
              <el-col>
                <el-form-item :label="`${subTitle}名称`" prop="roleName">
                  <el-input v-model="materForm.roleName" size="mini" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="isAddMaterriel = false">取 消</el-button>
        <!--  新建保存      -->
        <el-button
          v-loading="addMaterrielLoading"
          :disabled="addMaterrielLoading"
          element-loading-spinner="el-icon-loading"
          type="primary"
          size="mini"
          @click="addR"
        >保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { mapGetters } from 'vuex'
import checkboxTreeRender from './rendTree.vue'
import perRedioDialog from '@/components/perDialogRedio'
import perCheckDialog from '@/components/perDialogCheckbox'
export default {
  name: 'Materiel',
  components: { checkboxTreeRender, perRedioDialog, perCheckDialog },
  computed: {
    ...mapGetters(['name'])
  },
  data() {
    return {
      ops: 'add', // 基础数据操作、新建，修改，查看
      active: 0,
      subTitle: '角色',
      isperShow: false,
      userlList: [],
      permissionList:[],  //特殊权限列表
      isAddMaterriel: false, // 新建基础数据弹框是否打开
      addMaterrielLoading: false, // 新建基础数据保存加载
      classIndex: 0, // 选中分组索引
      allMaterielClass: [], // 所有基础数据分组
      // 新建基础数据表单
      // 基础表单
      chekedApis: [],
      selectData: null,
      selectRole: null,
      baseForm: {
        selectArr: [] // 用来接收选中的id值
      },
      materForm: {
        roleName: ''
      },
      columns: [
        { label: '菜单', prop: 'menuName' },
        { label: '权限', prop: 'buttons', type: 'template', template: 'buttons' }
      ],
      selectArr: [
      ],
      roleButtonPowerData: [],
      roleMenuPowerData: [],

      sourceData:[],

      // 基础数据搜索条件
      search: {
        pageIndex: 1,
        pageSize: 30,
        likeWords: '',
        dictionaryCode: '',
        dicValueState: 1
      },
      materFormRules: {
        roleName: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getMaterielClass()
  },
  mounted() {},
  updated() {},
  methods: {

    // 得到成员
    getEmployee(val) {
      const userIDs = []
      val.forEach(e => {
        userIDs.push(e.systemUserID)
      })
      this.$api.system
        .BatchChangeUsersRole({
          roleCode: this.selectRole.roleCode,
          userIDs: userIDs
        })
        .then((res) => {
          this.$message({
            message: '添加成功',
            type: 'success'
          })
          this.getUserList()
        })
    },
    handleCheckAllChange(data) {
      const { val, checked,buttons } = data
      if (val.buttons && val.buttons.length > 0) {
        // 处理按钮
        val.buttons.forEach((v) => {
          v.isHavePermission = checked
        })
      }
      if (val.chrildren && val.chrildren.length > 0) {
        // 处理下级
        this.findChildren(val.chrildren, checked)
      } else {
        // // 处理本级
        // val.chrildren.forEach((v) => {
        //   v.isHavePermission = checked
        // })
      }
      let state = true
      if(buttons){
        buttons.forEach((item)=>{
          if(!item.isHavePermission){
            state = false
          }
        })
      }
      if (state) {
        // 处理上级
        this.findParent(this.selectArr, val.parentCode)
      }
      val.indeterminate = false
    },
    // 设置子级
    findChildren(list, checked) {
      list.forEach((child) => {
        child.isHavePermission = checked
        child.indeterminate = false
        if (child.buttons && child.buttons.length > 0) {
        // 处理按钮
          child.buttons.forEach((v) => {
            v.isHavePermission = checked
          })
        }
        if (child.chrildren && child.chrildren.length > 0) {
          this.findChildren(child.chrildren, checked)
        }
      })
    },

    // 设置这一整条线
    findParent(list, parentCode) {
      list.forEach((k) => {
        this.handleList(k, parentCode)
        // if (k.menuTreeList) {
        //   k.menuTreeList.forEach((child) => {
        //     this.handleList(child, parentCode)
        //   })
        // } else {
        //   this.handleList(k, parentCode)
        // }
      })
    },
    // 设置这一整条线具体方法
    handleList(child, parentCode) {
      let parentCheckedLength = 0
      let parentIndeterminateLength = 0
      if (child.menuCode === parentCode) {
        if (child.buttons) {
          child.buttons.forEach((buttons) => {
            if (buttons.indeterminate) {
              parentIndeterminateLength++
            } else if (buttons.isHavePermission) {
              parentCheckedLength++
            }
          })
          // child.isHavePermission = parentCheckedLength === child.buttons.length
          // child.indeterminate = (parentIndeterminateLength > 0 || parentCheckedLength > 0) && parentCheckedLength < child.buttons.length
        }
        if (child.chrildren) {
          child.chrildren.forEach((chrildren) => {
            if (chrildren.indeterminate) {
              parentIndeterminateLength++
            } else if (chrildren.isHavePermission) {
              parentCheckedLength++
            }
          })
          // child.indeterminate = (parentIndeterminateLength > 0 || parentCheckedLength > 0) && parentCheckedLength < child.chrildren.length
        }
        child.isHavePermission = parentCheckedLength > 0
        if (child.parentCode !== -1) {
          this.findParent(this.selectArr, child.parentCode)
        }
      } else if (child.chrildren && child.chrildren.length > 0) {
        this.findParent(child.chrildren, parentCode)
      }
    },
    // tab切换
    changeTab(i) {
      this.active = i
    },
    // 删除基础数据分组
    deleteMaterielClass(data) {
      const parmas = {
        roleID: data.roleID
      }
      this.$confirm('确定删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$api.system.DeleteSystemRole(parmas).then(() => {
          this.getMaterielClass()
          this.$message({
            message: '删除成功',
            type: 'success'
          })
        })
      })
    },
    // 基础数据分组详情
    updateMaClass(data) {
      this.selectData = data
      this.materForm.roleName = data.roleName
      this.ops = 'edit'
      this.subTitle = '修改角色'
      this.isAddMaterriel = true
    },
    addRole() {
      this.ops = 'add'
      this.subTitle = '新建角色'
      this.isAddMaterriel = true
    },
    addR() {
      if (this.ops === 'add') {
        this.$api.system.AddSystemRole(this.materForm).then(() => {
          this.getMaterielClass()
          this.isAddMaterriel = false
          this.$message({
            message: '添加成功',
            type: 'success'
          })
        })
      } else {
        const parmas = {
          roleID: this.selectData.roleID,
          roleName: this.materForm.roleName
        }
        this.$api.system.UpdateSystemRole(parmas).then(() => {
          this.getMaterielClass()
          this.isAddMaterriel = false
          this.$message({
            message: '修改成功',
            type: 'success'
          })
        })
      }
    },
    addSelect() {
      this.roleButtonPowerData = []
      this.roleMenuPowerData = []
      this.ADDChangeSelect(this.selectArr)
      this.roleMenuPowerData = Array.from(new Set(this.roleMenuPowerData))
      this.$api.system
        .SureConfigRolesPermission({
          roleCode: this.selectRole.roleCode,
          roleMenuPowerData: this.roleMenuPowerData,
          roleButtonPowerData: this.roleButtonPowerData
        })
        .then((res) => {
          this.$message({
            message: '保存成功',
            type: 'success'
          })
          this.getSelectArr()
        })
    },

    ADDChangeSelect(arr) {
      arr.forEach(e => {
        if (e.isHavePermission) {
          this.roleMenuPowerData.push(e.menuCode)
        }
        if (e.buttons) {
          e.buttons.forEach(b => {
            if (b.isHavePermission) {
              this.roleButtonPowerData.push({
                menuCode: b.parentCode,
                buttonCode: b.menuCode
              })
            }
          })
        }
        if (e.chrildren) {
          e.chrildren.forEach(c => {
            if (c.isHavePermission) {
              this.roleMenuPowerData.push(c.menuCode)
            }
          })
          this.ADDChangeSelect(e.chrildren)
        }
      })
    },
    // 基础数据分组改变事件
    changeMaterClass(item, index) {
      this.selectRole = item
      this.classIndex = index
      this.getUserList()
      this.getSelectArr()
      this.getPermissionList()
    },

    //保存特殊权限
    savePermission(){
      console.log(this.permissionList)
      const obj = {
        roleCode:this.selectRole.roleCode,
        specificPermissionCodeList:this.permissionList.map(item=>{ if(item.isHavePower){return item.specificPermissionCode}else{ return ''} })
      }
      this.$api.system.SaveRoleSpecificPermission(obj).then(res=>{
        this.getPermissionList()
        this.$message.success('保存成功')
      })
    },

    //获取特殊权限列表
    getPermissionList(){
      this.$api.system.GetSpecificPermissionByRoleCode({roleCode:this.selectRole.roleCode}).then(res=>{
        this.permissionList = res
      })
    },

    // 获取用户列表
    getUserList() {
      this.$api.system
        .QueryMatchSystemUserDataList({
          roleCode: this.selectRole.roleCode,
          accountState: -1,
          likeWords: ''
        })
        .then((res) => {
          this.userlList = res
        })
    },
    // 获取权限
    getSelectArr() {
      this.$api.system
        .GetAccessDataBySystemRole({
          roleCode: this.selectRole.roleCode
        })
        .then((res) => {
          this.sourceData = res
          this.selectArr = this.changeSelect(res)
          console.log(this.selectArr)
        })
    },
    changeSelect(arr) {
      arr.forEach(e => {
        e.parentData = {
          isHavePermission:e.isHavePermission,
          menuCode:e.menuCode,
          menuName:e.menuName,
          parentCode:e.parentCode,
          data:this.sourceData
        }
        if (e.buttons) {
          for (let i = 0; i < e.buttons.length; i++) {
            e.buttons[i] = {
              parentCode: e.buttons[i].menuCode,
              menuCode: e.buttons[i].buttonCode,
              isHavePermission: e.buttons[i].isHavePermission,
              buttonName: e.buttons[i].buttonName,
            }
          }
          e.isSee = false
          e.num = 0
          e.buttons.forEach((item)=>{
            if(item.isHavePermission){
              e.num++
            }
          })
          if(e.isHavePermission && e.num==0){
            e.isSee = true
          }
        }

        if (e.chrildren) {
          this.changeSelect(e.chrildren)
        }else{

        }
      })
      return arr
    },
    // 获取所有左边分组
    getMaterielClass() {
      this.$api.system
        .QueryMatchSystemRoleDataList({
          likeWords: ''
        })
        .then((res) => {
          this.allMaterielClass = res
          this.selectRole = res[0]
          this.classIndex = 0
          this.getUserList()
          this.getSelectArr()
          this.getPermissionList()
        })
    },
    // 新建弹框关闭事件
    closeDialog() {
      if (this.$refs.materForm) {
        this.$refs.materForm.resetFields()
      }
      this.materForm = this.$options.data().materForm
    }
  }
}
</script>
<style lang="scss" scoped>
.materielList {
  max-height: calc(100vh - 190px);
  overflow-y: auto;
}
.addWuliaoBox {
  padding: 10px 16px;
}

.subTip {
  border-bottom: 1px #e6e6e6 solid;
  background: #f5f6f9;
  padding: 8px 16px;
}

.container {
  height: 100%;
}

.permangeRg {
  border: 1px solid #e6e6e6;
  background: #fff;
  margin-left: 10px;
  height: 100%;


  .mainTT {
    font-size: 16px;
    font-weight: bold;
    width: 100%;
    padding: 18px 16px;
    padding-bottom: 0;
  }
}

.permanageLf {
  width: 280px;
  height: 100%;
  border: 1px solid #e6e6e6;
  background: #fff;

  .kuOP {
    display: none;
  }

  li {
    padding: 9px 16px;
    cursor: pointer;

    &:hover {
      background: #3f61f110;
      color: #3f61f1;

      .kuOP {
        display: block !important;
      }
    }
  }

  li.on {
    background: #3f61f110;
    color: #3f61f1;
  }

  .allMateriel {
    line-height: 44px;
    padding-left: 16px;

    &:hover {
      background: #3f61f110;
      color: #3f61f1;
    }
  }

  .allMateriel.crt {
    background: #3f61f110;
    color: #3f61f1;
  }
}

.navTT {
  line-height: 22px;
  padding: 16px;
  border-bottom: 1px solid #e6e6e6;
}
.navtab {
  line-height: 22px;
  padding: 16px;
  border-bottom: 1px solid #e6e6e6;
  span {
    margin: 10px;
    padding: 18px 0;

    &.active {
      color: #3f61f1;
      border-bottom: 2px solid #3f61f1;
    }
  }
}
.selectWapper {
  background-color: #f2f2f6;
  margin: 16px;
  padding: 16px;
  .menu {
    width: 30%;
  }
}
.selectCpent {

}
.userWapper {
  margin: 16px;
}
.home {
  height: 617px;
  overflow: auto;
  .line {
    margin: 16px;
    // width: 60%;
    .check-group {
      width: 100%;
    }
  }
  .mmC {

  }
  .mm {
    // width: 50%;
  }
  .mmselect {
    display: flex;
    // margin-left: 28%;
  }
}
.areasOp {
  li {
    padding: 8px 16px;
    cursor: pointer;

    &:hover {
      background: #f6f6f6;
    }
  }
}
</style>
